#include <dspSimulator/instruction/clr.h>


bool CLR::checkCondition(std::shared_ptr<DspMachine> dspMachine) {
    if (isCompactInstruction) {
        return true;
    } else {
        return checkStandardCondition(dspMachine);
    }
}

void CLR::loadInstIRIntoJit(llvm::LLVMContext *llvmContext, llvm::Module *module,
                            std::shared_ptr<llvm::IRBuilder<>> irBuilder) {

}

std::shared_ptr<Instruction> CLR::decode(std::shared_ptr<InstInfo> instInfo, u64 baseCycle) {
    std::shared_ptr<CLR> clr;
    auto dspInstInfo = std::dynamic_pointer_cast<DspInstInfo>(instInfo);
    bool isStandardInst = dspInstInfo->isStandardInstruction();
    if (isStandardInst) {
        auto data = vectorToBitSet<32>(dspInstInfo->getBits());
        if (checkBits<6>(data, 2, 0b110010) && existStandardCondition(data)) {
            clr = std::make_shared<CLR>(dspInstInfo->getAddress(), baseCycle);
            clr->creg_z = extractBits<4>(data, 28);
            clr->dst = extractBits<5>(data, 23).to_ulong();
            clr->src2 = extractBits<5>(data, 18).to_ulong();
            clr->cst = extractBits<5>(data, 13).to_ulong();
            clr->auxCst = extractBits<5>(data, 8).to_ulong();
            clr->s = data[1];
            clr->p = data[0];
            if (clr->s == 0) {
                clr->funcUnit = FuncUnit::S1;
            } else {
                clr->funcUnit = FuncUnit::S2;
            }
            clr->instFormat = InstFormat::Kind1;
        }
    }
    return clr;
}

void CLR::executeCustom(std::shared_ptr<TargetMachine> targetMachine, ExecutePhase executePhase) {
    std::bitset<32> src2 = *src1LoRegPtr;
    switch (instFormat) {
        case InstFormat::Kind1:
            for (u32 i = 0; i < 32; ++i) {
                if (i >= cst && i <= auxCst) {
                    src2[i] = 0;
                }
            }
            *dstLoRegPtr = src2.to_ulong();
            break;
        default:
            break;
    }
}

std::string CLR::toString() const {
    std::string res;
    if (!isCompactInstruction) {
        res += getStandardConditionString() + " ";
    }
    res += m_name + " " + FuncUnitName[static_cast<u32>(funcUnit)] + " ";
    if (instFormat == InstFormat::Kind1) {
        res += getSrc2Reg32Name() + "," + std::to_string(cst) + "," + std::to_string(auxCst) + "," + getDstReg32Name();
    }
    return res;
}

std::shared_ptr<DspInstruction> CLR::clone() {
    return std::make_shared<CLR>(*this);
}
